package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.controller.OrderInfoController;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit


    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 订单结算
     *
     * @return 结算明细
     */
    @Override
    public TradeVo orderTradeData() {
        //1.获取用户id
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedListR = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);//调用购物车微服务
        if (R.FAIL == cartCheckedListR.getCode()) {//判断调用是否成功
            throw new ServiceException(cartCheckedListR.getMsg());//调用失败则抛出异常
        }

        List<CartInfo> cartInfoList = cartCheckedListR.getData();//获取购物车选中的商品列表
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("请选中购买的商品");
        }
        //将集合泛型从购物车改为订单明细
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();//创建订单明细对象
            BeanUtils.copyProperties(cartInfo, orderItem);//将购物车中的商品信息复制到订单明细中
//            orderItem.setSkuPrice(cartInfo.getSkuPrice());
            return orderItem;
        }).toList();

        BigDecimal totalAmount = BigDecimal.ZERO;//订单总金额
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //渲染订单确认页面-生成用户流水号
        String tradeNo = this.generateTradeNo(userId);//调用生成流水号方法 生成流水号

        TradeVo tradeVo = new TradeVo(); //创建交易页面数据回显的数据模型类对象
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    /**
     * 生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //构建流水号key
        String userTradeKey = "user:tradeNo" + userId;
        //构建流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        //将流水号存入redis 暂存 5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     *
     * @param userId
     * @param tradeNo
     * @return
     */
    public Boolean checkTradeNo(String userId, String tradeNo) {
        String userTradekey = "user:tradeNo" + userId; //构建流水号key
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradekey); //获取redis中的流水号
        return tradeNo.equals(redisTradeNo);//比较流水号是否一致
    }

    /**
     * 删除流水号
     * @param userId
     */
    public void deleteTradeNo(String userId) {
        String userTradeKey = "user:tradeNo" + userId;
        redisTemplate.delete(userTradeKey);
    }

    /**
     * 提交订单
     *
     * @return 订单id
     */
    @Transactional(rollbackFor = Exception.class)
    //明确指定捕获所有异常（包括受检异常）并回滚事务。 如果不指定，默认情况下，只有未检查的异常（如 RuntimeException）才会触发回滚。
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1.获取用户id
        String tradeNo = orderForm.getTradeNo(); //获取页面提交的流水号
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo" + userId; //构建流水号key
        log.info("订单表单：{}", orderForm);
        //1.验证用户是否通过浏览器回退进行重复提交订单
        //1.1 获取Redis中存放流水号 跟用户提交比较
        //1.2 验证通过，将Redis中存放流水号删除
        //this.deleteTradeNo(orderInfo.getUserId().toString());
        //1.3 采用Lua脚本保证判断删除流水号原子性 KEYS[1]:流水号Key    ARGV[1]：用户流水号
        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then \n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();  //创建Redis脚本对象
        redisScript.setScriptText(script);//设置脚本文本
        redisScript.setResultType(Long.class);//设置返回类型

        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNo);
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请尝试刷新页面重新提交订单");
        }

        //2. 判断购物项
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        log.info("订单明细列表: {}", orderItemList != null ? orderItemList : "空");

        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("没有选中购买的商品，请求不合法");
        }
        //3.订单校验
        //3.1.校验价格 //将集合转成流   //获取每个元素的skuIdOrder   // Item::getSkuId 是方法引用，等价于 item -> item.getSkuId()，表示提取每个 OrderItem 的 skuId。// 收集结果到List中
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());

        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        //获取商品价格列表
        List<SkuPrice> skuPricesList = skuPriceListResult.getData();
        //将商品价格列表转成Map
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPricesList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        String priceCheckResult = "";//价格校验结果
        //orderFormd 的 orderItemList结算商品列表
        //遍历结算商品列表
        for (OrderItem orderItem : orderItemList) {
            //页面提交表单的价格跟数据库查询的价格比较
            if (orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId())) != 0) {
                priceCheckResult += orderItem.getSkuName() + "价格变化了；";
            }
        }
        //价格校验结果不为空，说明价格有变化
        if (StringUtils.isNotEmpty(priceCheckResult)) {
            //更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(priceCheckResult + "重新提交订单");
        }

        //3.2.校验库存并锁定库存
        //TODO ....
        Long orderId = null;
        try {
            //4 下单
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //抛出异常
            throw new ServiceException("下单失败");
        }

        //5 删除购物车选项
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        return orderId;
    }
    /**
     * 保存订单
     *
     * @return 订单id
     */
    //保存订单
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm) {
        //1.获取用户id
        Long userId = SecurityContextHolder.getUserId();
        //2.获取用户姓名
        String userName = SecurityContextHolder.getUserName();
        //订单表 order_info  订单明细表 order_item  订单日志表 order_log
        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());

        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //计算订单总额
        List<OrderItem> orderItemList = orderForm.getOrderItemList();//获取结算商品列表

        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);//它将 orderInfo 对象的属性值映射到数据库表的对应列，并执行 INSERT 操作。

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }
        //记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");

        return orderInfo.getId();
    }
}